package com.qsmx.qingqiuticket.app.delegate;

import static androidx.core.content.ContextCompat.registerReceiver;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.content.ContextCompat;

import com.al.printerlib.cmd.GetStatusCmd;
import com.al.printerlib.cmd.Pdf417;
import com.al.printerlib.device.CallbackListener;
import com.al.printerlib.device.Printer;
import com.al.printerlib.device.PrinterStatus;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.log.AtmosLogger;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateUsbPrintHomeBinding;
import com.qsmx.qingqiuticket.app.delegate.adapter.AppTypeSpanAdapter;
import com.qsmx.qingqiuticket.app.event.HomeRefreshEvent;
import com.qsmx.qingqiuticket.app.event.UsbEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.fusion.FusionTag;
import com.qsmx.qingqiuticket.app.util.DownloadUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class UsbPrintHomeDelegate extends AtmosDelegate {
    UsbManager manager;
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private List<UsbDevice> mUsbList;
    private String mUsbNum;
    private Printer mDevice;

    private boolean isFirst = false;

    private String checkPermissionPrintNo = "";

    private DelegateUsbPrintHomeBinding mBindView;

    @Override
    public Object setLayout() {
        return R.layout.delegate_usb_print_home;
    }

    public static UsbPrintHomeDelegate create(boolean isFirst) {

        final Bundle args = new Bundle();
        args.putBoolean(FusionTag.IS_FIRST, isFirst);

        final UsbPrintHomeDelegate delegate = new UsbPrintHomeDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            isFirst = args.getBoolean(FusionTag.IS_FIRST);
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        mBindView = DelegateUsbPrintHomeBinding.bind(rootView);
        if (isFirst) {
            mBindView.tvBack.setText("确定");
        } else {
            mBindView.tvBack.setText("返回");
        }
        startPermiss();

        initPrint1TypeSpanInfo();
        initPrint2TypeSpanInfo();
        initPrint3TypeSpanInfo();
        getUsbDeviceList();

        mBindView.tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFirst) {
                    if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE))) {
                        DialogUtil.showCardErrorDialog(requireContext(), "请确认已设置打印机-1", "确定");
                        return;
                    }
                    if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO))) {
                        DialogUtil.showCardErrorDialog(requireContext(), "请确认已设置打印机-2", "确定");
                        return;
                    }
                    if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE))) {
                        DialogUtil.showCardErrorDialog(requireContext(), "请确认已设置打印机-3", "确定");
                        return;
                    }
                    getSupportDelegate().popTo(IndexDelegate.class, false);
                    EventBus.getDefault().post(new HomeRefreshEvent(new Bundle()));
                } else {
                    getSupportDelegate().pop();
                }
            }
        });

        mBindView.tvPrintTest1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint1No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint1No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "print");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvGoPaper1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint1No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint1No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "print_no_cut");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvGetPrint1Status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint1No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint1No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "get_status");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });


        mBindView.tvPrintTest2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint2No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint2No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "print");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvGoPaper2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint2No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint2No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "print_no_cut");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvGetPrint2Status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint2No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint2No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "get_status");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });
        mBindView.tvPrintTest3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint3No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint3No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "print");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvGoPaper3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint3No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint3No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "print_no_cut");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvGetPrint3Status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint3No.getSelectedItem().toString().equals("请选择")) {
                    String deviceName = checkDeviceName(mBindView.spPrint3No.getSelectedItem().toString());
                    connectUsbDevice(mDevice, deviceName, "get_status");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                }
            }
        });

        mBindView.tvPrintSave1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint1No.getSelectedItem().toString().equals("请选择")) {
                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE, mBindView.spPrint1No.getSelectedItem().toString());
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机1保存成功", "确定");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "请选择打印机", "确定");
                }
            }
        });
        mBindView.tvPrintSave2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint2No.getSelectedItem().toString().equals("请选择")) {
                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO, mBindView.spPrint2No.getSelectedItem().toString());
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机2保存成功", "确定");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "请选择打印机", "确定");
                }
            }
        });
        mBindView.tvPrintSave3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mBindView.spPrint3No.getSelectedItem().toString().equals("请选择")) {
                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE, mBindView.spPrint3No.getSelectedItem().toString());
                    DialogUtil.showCardErrorDialog(requireContext(), "打印机3保存成功", "确定");
                } else {
                    DialogUtil.showCardErrorDialog(requireContext(), "请选择打印机", "确定");
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUsbEvent(UsbEvent event) {
        if (event != null && event.getData() != null) {
//            String name = event.getData().getString("usbName");
//            String usbNum = event.getData().getString("usbNum");
//            if (usbNum.equals("1")) {
//                if (mDevice1 != null) {
//                    mDevice1.ClosePort();
//                    mDevice1 = null;
//                }
//                mDevice1 = new Printer(requireContext(), name, this);
//                mDevice1.OpenPort();
//            } else if (usbNum.equals("2")) {
//                if (mDevice2 != null) {
//                    mDevice2.ClosePort();
//                    mDevice2 = null;
//                }
//                mDevice2 = new Printer(requireContext(), name, this);
//                mDevice2.OpenPort();
//            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mDevice = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private boolean printSample(Printer device) {
        try {
            device.InitPrinter();

            device.EnablePM();
            device.SetPrnAreaInPM(5 * 8, 160 * 8, 70 * 8, 35 * 8);
            device.SetDirectionInPM(3);
            //Print text
//            device.SetLeftMargin(0);
            device.SetTextMultiple(1, 1);
            device.LineFeed();
            device.SetAbsHoriPrnPos(40);
            device.PrintText("奥特曼俱乐部");
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.SetAbsHoriPrnPos(50);
            device.SetQrParameter(6, 49);
            device.PrintQrCode("12345123451234512345123451234512345123451234512345");
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.LineFeed();
            device.SetAbsHoriPrnPos(30);
            device.PrintText("场次：A");
            device.LineFeed();
            device.SetAbsHoriPrnPos(30);
            device.PrintText("时间：2025.04.01");
            device.PrintPage();
            device.CutPaperEx(0);
            device.ResetPrinter();
            device.ClosePort();
            device = null;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            DialogUtil.showCardErrorDialog(requireContext(), "打印失败,打印机初始化异常", "确定");
            return false;
        }
    }

    private boolean printNoCutSample(Printer device) {
        try {
            device.InitPrinter();
//            device.EnablePM();
//            device.SetPrnAreaInPM()
//            device.SetDirectionInPM(3);
            //Print text
            device.FeedPaper(200);
//            device.CutPaperEx(0);
//            device.PrintPage();
            device.ResetPrinter();
            device.ClosePort();
            device = null;
            mDevice = null;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            DialogUtil.showCardErrorDialog(requireContext(), "打印失败,打印机初始化异常", "确定");
            return false;
        }
    }

    /**
     * 检查USB设备的PID与VID
     *
     * @param dev
     * @return
     */
    boolean checkUsbDevicePidVid(UsbDevice dev) {
        int pid = dev.getProductId();
        int vid = dev.getVendorId();
        return (vid == 0x5a5a && pid == 0x8009);
    }

    /**
     * 获取USB设备列表
     */
    @SuppressLint("NotifyDataSetChanged")
    public void getUsbDeviceList() {
        mUsbList = new ArrayList<>();
        manager = (UsbManager) getProxyActivity().getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devices = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = devices.values().iterator();
        int count = devices.size();
        AtmosLogger.d("count " + count);
        if (count > 0) {
            while (deviceIterator.hasNext()) {
                UsbDevice device = deviceIterator.next();
                PendingIntent mPermissionIntent = PendingIntent.getBroadcast(getContext(), 0,
                        new Intent(ACTION_USB_PERMISSION),
                        Build.VERSION.SDK_INT >= 34 ? PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_MUTABLE);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);//USB插入
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);//USB拔出
                registerReceiver(requireContext(), mUsbReceiver, filter, ContextCompat.RECEIVER_EXPORTED);

                if (manager.hasPermission(device)) {
                    if (checkUsbDevicePidVid(device)) {
                        mUsbList.add(device);
                    }
                } else {
                    //请求USB设备权限
                    manager.requestPermission(device, mPermissionIntent);
                }
            }
        } else {
            String noDevices = getResources().getText(R.string.none_usb_device).toString();
            AtmosLogger.d("noDevices " + noDevices);
        }

        if (mUsbList != null && !mUsbList.isEmpty()) {
            initPrint1SpanInfo();
            initPrint2SpanInfo();
            initPrint3SpanInfo();
        } else {
            AtmosLogger.d("mUsbList is null");
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    public String checkDeviceName(String PrintNo) {
        String deviceName = "";
        mUsbList = new ArrayList<>();
        manager = (UsbManager) getProxyActivity().getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devices = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = devices.values().iterator();
        int count = devices.size();
        AtmosLogger.d("count " + count);
        if (count > 0) {
            while (deviceIterator.hasNext()) {
                UsbDevice device = deviceIterator.next();
                if (checkUsbDevicePidVid(device)) {
                    mUsbList.add(device);
                }
            }
        } else {
            String noDevices = getResources().getText(R.string.none_usb_device).toString();
            AtmosLogger.d("noDevices " + noDevices);
        }

        if (mUsbList != null && !mUsbList.isEmpty()) {
            for (UsbDevice device : mUsbList) {
                if (Objects.equals(device.getSerialNumber(), PrintNo)) {
                    deviceName = device.getDeviceName();
                }
            }
        }
        return deviceName;
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            if (getSupportDelegate().isSupportVisible()) {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this) {
                        UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if (device != null) {
                                if (checkUsbDevicePidVid(device)) {
                                    mUsbList.add(device);
                                }
                                Toast.makeText(context, "设备授权成功", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(context, "设备拒绝授权", Toast.LENGTH_LONG).show();
                        }
                    }
                } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    Toast.makeText(context, "USB已插入", Toast.LENGTH_LONG).show();
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    Toast.makeText(context, "USB已拔出", Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    private String setPrintStatus(PrinterStatus printStatus) {
        if (printStatus.bPrinterStatePaperEnd) {
            return "纸张不足";
        } else if (printStatus.bPrinterStatePaperNearEnd) {
            return "纸将尽";
        } else if (printStatus.bPrinterStatePlateOpen) {
            return "开盖错误";
        } else if (printStatus.bPrinterStateCutterError) {
            return "切刀错误";
        } else if (printStatus.bPrinterStateHighTmError) {
            return "热敏感问多过高";
        } else if (printStatus.bPrinterStatePaperJam) {
            return "堵纸错误";
        } else if (printStatus.bPrinterStateHighVoltage) {
            return "高压错误";
        } else if (printStatus.bPrinterStateLowVoltage) {
            return "低压错误";
        } else if (printStatus.bPrinterStateBlackMarkError) {
            return "黑标错误";
        } else if (printStatus.bPrinterStatePrinting) {
            return "正在打印";
        } else if (printStatus.bPrinterStateTestPrinting) {
            return "正在打印自检页";
        } else if (printStatus.bPrinterStateRedundantError) {
            return "冗纸错误";
        } else if (printStatus.bPrinterStateRamError) {
            return "RAM错误";
        }
        return "正常";
    }


    private void initPrint1TypeSpanInfo() {
        List<String> mPrintTypeList = new ArrayList<>();
        mPrintTypeList.add("X80");
        mPrintTypeList.add("请选择");

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mPrintTypeList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBindView.spPrint1Type.setAdapter(arrAdapter);
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TYPE))) {
            mBindView.spPrint1Type.setSelection(mPrintTypeList.size() - 1, true);
        } else {
            for (int i = 0; i < mPrintTypeList.size(); i++) {
                if (mPrintTypeList.get(i).equals(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TYPE))) {
                    mBindView.spPrint1Type.setSelection(i, true);
                }
            }
        }
        mBindView.spPrint1Type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_TYPE, mPrintTypeList.get(position));
                getUsbDeviceList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initPrint2TypeSpanInfo() {
        List<String> mPrintTypeList = new ArrayList<>();
        mPrintTypeList.add("X80");
        mPrintTypeList.add("请选择");

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mPrintTypeList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBindView.spPrint2Type.setAdapter(arrAdapter);
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TYPE))) {
            mBindView.spPrint2Type.setSelection(mPrintTypeList.size() - 1, true);
        } else {
            for (int i = 0; i < mPrintTypeList.size(); i++) {
                if (mPrintTypeList.get(i).equals(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TYPE))) {
                    mBindView.spPrint2Type.setSelection(i, true);
                }
            }
        }
        mBindView.spPrint2Type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_TYPE, mPrintTypeList.get(position));
                getUsbDeviceList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initPrint3TypeSpanInfo() {
        List<String> mPrintTypeList = new ArrayList<>();
        mPrintTypeList.add("X80");
        mPrintTypeList.add("请选择");

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mPrintTypeList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBindView.spPrint3Type.setAdapter(arrAdapter);
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TYPE))) {
            mBindView.spPrint3Type.setSelection(mPrintTypeList.size() - 1, true);
        } else {
            for (int i = 0; i < mPrintTypeList.size(); i++) {
                if (mPrintTypeList.get(i).equals(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TYPE))) {
                    mBindView.spPrint3Type.setSelection(i, true);
                }
            }
        }
        mBindView.spPrint3Type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_TYPE, mPrintTypeList.get(position));
                getUsbDeviceList();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initPrint1SpanInfo() {
        List<String> mUsbNameList = new ArrayList<>();
        for (UsbDevice usbDevice : mUsbList) {
            mUsbNameList.add(usbDevice.getSerialNumber());
        }
        mUsbNameList.add("请选择");
        int selectPort = mUsbNameList.size() - 1;

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mUsbNameList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBindView.spPrint1No.setAdapter(arrAdapter);
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE))) {
            mBindView.spPrint1No.setSelection(mUsbNameList.size() - 1, true);
        } else {
            for (int i = 0; i < mUsbNameList.size(); i++) {
                if (mUsbNameList.get(i).equals(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE))) {
                    selectPort = i;
                }
            }
            mBindView.spPrint1No.setSelection(selectPort, true);
        }
        mBindView.spPrint1No.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initPrint2SpanInfo() {
        List<String> mUsbNameList = new ArrayList<>();
        for (UsbDevice usbDevice : mUsbList) {
            mUsbNameList.add(usbDevice.getSerialNumber());
        }
        mUsbNameList.add("请选择");
        int selectPort = mUsbNameList.size() - 1;

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mUsbNameList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBindView.spPrint2No.setAdapter(arrAdapter);
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO))) {
            mBindView.spPrint2No.setSelection(mUsbNameList.size() - 1, true);
        } else {
            for (int i = 0; i < mUsbNameList.size(); i++) {
                if (mUsbNameList.get(i).equals(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO))) {
                    selectPort = i;
                }
            }
            mBindView.spPrint2No.setSelection(selectPort, true);
        }
        mBindView.spPrint2No.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initPrint3SpanInfo() {
        List<String> mUsbNameList = new ArrayList<>();
        for (UsbDevice usbDevice : mUsbList) {
            mUsbNameList.add(usbDevice.getSerialNumber());
        }
        mUsbNameList.add("请选择");
        int selectPort = mUsbNameList.size() - 1;

        //适配器
        AppTypeSpanAdapter<String> arrAdapter = new AppTypeSpanAdapter<String>(requireContext(), R.layout.simple_spinner_item, mUsbNameList);
        //设置样式
        arrAdapter.setDropDownViewResource(R.layout.dropdown_stytle);
        //加载适配器
        mBindView.spPrint3No.setAdapter(arrAdapter);
        if (StringUtil.isEmpty(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE))) {
            mBindView.spPrint3No.setSelection(mUsbNameList.size() - 1, true);
        } else {
            for (int i = 0; i < mUsbNameList.size(); i++) {
                if (mUsbNameList.get(i).equals(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE))) {
                    selectPort = i;
                }
            }
            mBindView.spPrint3No.setSelection(selectPort, true);
        }
        mBindView.spPrint3No.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void connectUsbDevice(Printer mPrinter, String serialNumber, String type) {
        mDevice = new Printer(requireContext(), serialNumber, new CallbackListener() {
            @Override
            public void onConnecting() {
                AtmosLogger.d("连接中...");
            }

            @Override
            public void onSuccess(String name) {
                if (type.equals("print")) {
                    printSample(mDevice);
                } else if (type.equals("print_no_cut")) {
                    printNoCutSample(mDevice);
                } else if (type.equals("get_status")) {
                    DialogUtil.showCardErrorDialog(requireContext(), "正在获取打印机状态...", "确定");
                    if (mDevice != null) {
                        PrinterStatus test = getPrinterStatus(mDevice, 500);
                        if (test != null) {
                            DialogUtil.setErrorInfo(setPrintStatus(test));
                        } else {
                            DialogUtil.setErrorInfo("打印机连接超时");
                        }
                    } else {
                        DialogUtil.showCardErrorDialog(requireContext(), "打印机未连接", "确定");
                    }
                }
            }

            @Override
            public void onReceive(byte[] data) {

            }

            @Override
            public void onFailure() {
                AtmosLogger.d("连接失败");
            }

            @Override
            public void onDisconnect() {
                AtmosLogger.d("断开连接");
            }
        });
        mDevice.OpenPort();
    }

    private static PrinterStatus getPrinterStatus(Printer device, int timeoutms) {
        PrinterStatus pst = new PrinterStatus();
        int result = device.GetStatus(pst, timeoutms);
        if (result != 0) {
            return null;
        }
        return pst;
    }


    private void startPermiss() {
        UsbPrintHomeDelegatePermissionsDispatcher.startCheckUpdateWithCheck(UsbPrintHomeDelegate.this);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startCheckUpdate() {
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onFileRational(PermissionRequest request) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UsbPrintHomeDelegatePermissionsDispatcher.onRequestPermissionsResult(UsbPrintHomeDelegate.this, requestCode, grantResults);
    }

}
